<template>
    <div id="monitor-rule-detail">
        <div class="title-with-box">
            <el-divider content-position="left">基本信息</el-divider>
            <el-form label-width="110px">
                <el-row>
                    <el-form-item label="监控规则名称:">
                        <el-input v-model="submitForm.ruleName" :disabled="isLook" clearable size="mini"></el-input>
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item label="备注:">
                        <el-input v-model="submitForm.remark" :disabled="isLook" clearable size="mini"></el-input>
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item label="启用状态:">
                        <el-switch v-model="submitForm.status" :disabled="isLook" active-value="1" inactive-value="0"> </el-switch>
                    </el-form-item>
                </el-row>
            </el-form>
        </div>
        <div class="title-with-box">
            <el-divider content-position="left">监控频率</el-divider>
            <el-row class="frequency-box">
                <el-col :span="2">
                    <i class="el-icon-plus" @click="addFrequency"></i>
                </el-col>
                <el-col :span="4" style="line-height: 28px"><span class="red">*</span> 调度类型 </el-col>
                <el-col :span="8" style="line-height: 28px"><span class="red">*</span> 表达式 </el-col>
            </el-row>

            <el-row v-for="(i, index) in taskList" :key="index" class="frequency-box">
                <el-col :span="2">
                    <i class="el-icon-minus" @click="deleteFrequency(index)"></i>
                </el-col>
                <el-col :span="4">
                    <el-select v-model="i.scheduleType" :disabled="isLook" size="mini">
                        <el-option label="CRON" value="cron"></el-option>
                    </el-select>
                </el-col>
                <el-col :span="8">
                    <el-popover v-model="i.cronPopover">
                        <VueCron
                            @change="
                                val => {
                                    i.expression = val;
                                }
                            "
                            @close="i.cronPopover = false"
                            i18n="cn"
                        ></VueCron>
                        <el-input
                            slot="reference"
                            @click="i.cronPopover = true"
                            v-model="i.expression"
                            :disabled="isLook"
                            placeholder="示例：0 0/5 '' ?"
                            clearable
                            size="mini"
                        ></el-input>
                    </el-popover>
                </el-col>
            </el-row>
        </div>
        <div class="title-with-box">
            <el-divider content-position="left">监控逻辑</el-divider>

            <div class="logic-box">
                <el-card class="flex1">
                    <p>Aggredator(采集器) <el-button @click="handleAggregator('add')" size="mini" icon="el-icon-plus"></el-button></p>
                    <ul>
                        <li v-for="(i, index) in dataAggregatorList" :key="index">
                            <span class="title">{{ i.gatherName || '-' }}</span>
                            <div class="btn">
                                <span class="link" @click="handleAggregator('look', i)">查看</span>
                                <span class="link" v-show="!isLook" @click="handleAggregator('edit', i, index)">编辑</span>
                                <span class="link red" v-show="!isLook" @click="handleAggregator('delete', i, index)">删除</span>
                            </div>
                        </li>
                    </ul>
                </el-card>
                <el-card class="flex1" style="margin: 0 10px">
                    <p>Comparator(比较器) <el-button @click="handleComparator('add')" size="mini" icon="el-icon-plus"></el-button></p>
                    <ul>
                        <li v-for="(i, index) in dataComparatorList" :key="index">
                            <span class="title">{{ i.compareName || '-' }}</span>
                            <div class="btn">
                                <span class="link" @click="handleComparator('look', i)">查看</span>
                                <span class="link" v-show="!isLook" @click="handleComparator('edit', i, index)">编辑</span>
                                <span class="link red" v-show="!isLook" @click="handleComparator('delete', i, index)">删除</span>
                            </div>
                        </li>
                    </ul>
                </el-card>
                <el-card class="flex1">
                    <p>
                        alarum(报警器) <el-button @click="handleAlerter('add')" size="mini" icon="el-icon-plus"></el-button>
                        <el-button @click="handleAlerter('auto')" size="mini" style="float: right" type="primary">自动生成</el-button>
                    </p>
                    <ul>
                        <li v-for="(i, index) in dataAlerterList" :key="index">
                            <span class="title">{{ i.alertrtName || '-' }}</span>
                            <div class="btn">
                                <span class="link" @click="handleAlerter('look', i)">查看</span>
                                <span class="link" v-show="!isLook" @click="handleAlerter('edit', i, index)">编辑</span>
                                <span class="link red" v-show="!isLook" @click="handleAlerter('delete', i, index)">删除</span>
                            </div>
                        </li>
                    </ul>
                </el-card>
            </div>
        </div>
        <div class="title-with-box">
            <el-divider content-position="left">可视化</el-divider>
            <div style="padding: 0 10px 10px 10px">
                <p>请输入表头配置JSON <span class="link" style="margin-left: 10px" @click="lookColumns">预览</span></p>

                <el-tag
                    v-for="(item, index) in items"
                    :key="index"
                    :type="item.type"
                    @click="handleTag(item.label)"
                    size="mini"
                    effect="dark"
                    class="tags"
                >
                    {{ item.label }}
                </el-tag>

                <el-row v-show="showJsonBoolean">
                    <el-table ref="emailTable" :data="emailTable" border size="mini" style="width: 100%">
                        <el-table-column v-for="i in emailTableColumns" :prop="i.field" :key="i.field" :label="i.title" min-width="100">
                        </el-table-column>
                    </el-table>
                </el-row>
                <el-input
                    id="myInput"
                    v-model="submitForm.showJson"
                    :disabled="isLook"
                    placeholder='例:[{"HS_C_STOCK_CODE":"恒生证券代码"},{"RISK_C_STOCK_CODE":"风控证券代码"}, {"HS_C_STOCK_NAME":"恒生证券名称"}]'
                    :rows="6"
                    type="textarea"
                    size="mini"
                ></el-input>
            </div>
        </div>

        <el-row class="search-bar">
            <el-col :span="24" style="text-align: right">
                <el-button size="mini" @click="cancel"> 取 消 </el-button>
                <el-button size="mini" type="primary" @click="submit" v-if="!isLook"> 确 认 </el-button>
            </el-col>
        </el-row>

        <!-- Aggredator采集器Dialog -->
        <AggregatorDialog
            v-if="aggregatorVisible"
            :visible.sync="aggregatorVisible"
            :type="currentType"
            :detail="detailMsg"
            @submit="handleAggregatorSubmit"
        />
        <!-- Comparator比较器Dialog -->
        <ComparatorDialog
            v-if="comparatorVisible"
            :visible.sync="comparatorVisible"
            :type="currentType"
            :detail="detailMsg"
            @submit="handleComparatorSubmit"
        />
        <!-- alarum报警器Dialog -->
        <AlerterDialog
            v-if="alerterVisible"
            :visible.sync="alerterVisible"
            :type="currentType"
            :detail="detailMsg"
            :totalData="submitForm"
            :dataComparatorList="dataComparatorList"
            :OreceiveUser="OreceiveUser"
            :OcopyUser="OcopyUser"
            @submit="handleAlerterSubmit"
        />
    </div>
</template>
<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
import { AggregatorVO, AlerterVO, ComparatorVO, MonitorRuleSubmitFormDTO, MonitoRuleTaskVO } from '../vo/monitor-rule-setting';
import AggregatorDialog from './aggregator-dialog.vue';
import ComparatorDialog from './comparator-dialog.vue';
import AlerterDialog from './alerter-dialog.vue';
import DictionConstUtil, { objToArr } from '@/utils/diction-const-util';
import API from '../api/monitor-rule-setting';
import VueCron from '@/common/components/cron/src/index.vue';
import { ColumnVO } from '@/common/vo';

@Component({ name: 'MonitorRuleDetail', components: { AggregatorDialog, ComparatorDialog, AlerterDialog, VueCron } })
export default class MonitorRuleDetail extends Vue {
    @Prop() detail: any;

    submitForm: MonitorRuleSubmitFormDTO = {
        ruleName: '',
        remark: '',
        status: '1',
        taskList: [],
        dataAggregatorList: [],
        dataComparatorList: [],
        dataAlerterList: [],
        showJson: '', // 可视化JSON
    };
    taskList: MonitoRuleTaskVO[] = []; // 监控频率
    dataAggregatorList: AggregatorVO[] = []; // Aggredator采集器
    dataComparatorList: ComparatorVO[] = []; // Comparator比较器
    dataAlerterList: AlerterVO[] = []; // alarum报警器

    aggregatorVisible: boolean = false; // Aggredator采集器Dialog
    comparatorVisible: boolean = false; // Comparator比较器Dialog
    alerterVisible: boolean = false; // alarum报警器Dialog
    detailMsg: any = {};
    currentType: string = ''; // add | look | edit | delete
    currentIndex: number;

    emailTable: any[] = [{}]; // 预览表格
    emailTableColumns: any[] = [];
    showJsonBoolean: boolean = false;
    type: string = ''; // add | look | edit

    items: any[] = [
        // { type: '', label: '标签一' },
        // { type: 'success', label: '标签二' },
        // { type: 'info', label: '标签三' },
        // { type: 'danger', label: '标签四' },
        // { type: 'warning', label: '标签五' },
        // { type: '', label: '标签一' },
        // { type: 'success', label: '标签二' },
        // { type: 'info', label: '标签三' },
        // { type: 'danger', label: '标签四' },
        // { type: 'warning', label: '标签五' },
        // { type: '', label: '标签一' },
        // { type: 'success', label: '标签二' },
        // { type: 'info', label: '标签三' },
        // { type: 'danger', label: '标签四' },
        // { type: 'warning', label: '标签五' },
        // { type: '', label: '标签一' },
        // { type: 'success', label: '标签二' },
        // { type: 'info', label: '标签三' },
        // { type: 'danger', label: '标签四' },
        // { type: 'warning', label: '标签五' },
        // { type: '', label: '标签一' },
        // { type: 'success', label: '标签二' },
        // { type: 'info', label: '标签三' },
        // { type: 'danger', label: '标签四' },
        // { type: 'warning', label: '标签五' },
        // { type: '', label: '标签一' },
        // { type: 'success', label: '标签二' },
        // { type: 'info', label: '标签三' },
        // { type: 'danger', label: '标签四' },
        // { type: 'warning', label: '标签五' },
    ];

    OreceiveUser: any[] = [];
    OcopyUser: any[] = [];

    mounted() {
        if (['look', 'edit', 'copy'].includes(this.detail?.name)) {
            // this.submitForm = JSON.parse(JSON.stringify(this.detail.detail));
            // this.taskList = this.submitForm.taskList;
            // this.dataAggregatorList = this.submitForm.dataAggregatorList;
            // this.dataComparatorList = this.submitForm.dataComparatorList;
            // this.dataAlerterList = this.submitForm.dataAlerterList;
            this.getDetailMsg();
        }
        this.type = this.detail.name;

        // 获取预设收件人
        API.getSystemValue(['devops-receiveUser']).then(res => (this.OreceiveUser = res || []));
        // 获取预设抄送人
        API.getSystemValue(['devops-copyUser']).then(res => (this.OcopyUser = res || []));
    }

    get isLook() {
        return this.type === 'look';
    }

    /**
     * 获取
     */
    getDetailMsg(): void {
        console.log(this.detail, 'this.detail');

        API.getMonitorRuleDetail(this.detail.detail.id).then((res: any) => {
            this.submitForm = res;
            this.taskList = this.submitForm.taskList || [];
            this.dataAggregatorList = this.submitForm.dataAggregatorList || [];
            this.dataComparatorList = this.submitForm.dataComparatorList || [];
            this.dataAlerterList = this.submitForm.dataAlerterList || [];

            let fieldList;
            // 获取采集器的字段
            fieldList = this.dataAggregatorList.filter(i => i.processType === 'COMPOSE').map(i => i.logicContext);
            // 获取比较器的字段
            let compare = this.dataComparatorList.map(i => i.checkRuleContext);
            fieldList = [...fieldList, ...compare].join(',');
            this.getfieldTags(fieldList);
        });
    }

    /**
     * 新增监控频率
     */
    addFrequency(): void {
        if (this.isLook) return;
        if (this.taskList.length >= 10) {
            this.yh_message_warn('监控频率最多设置10条!');
            return;
        }
        this.taskList.push({ scheduleType: 'cron', expression: '' });
    }

    /**
     * 删除监控频率
     * @param index 所处下标
     */
    deleteFrequency(index: number): void {
        if (this.isLook) return;
        // if (this.taskList.length === 1) {
        //     this.yh_message_warn('监控频率最少设置1条!');
        //     return;
        // }
        this.taskList = this.taskList.filter((i, index1) => index1 !== index);
    }

    /**
     * 采集器事件
     * @param type 类型 add | look | edit | delete
     * @param data row数据
     * @param index 下标
     */
    handleAggregator(type: string, data: any = {}, index: number): void {
        if (this.isLook && type !== 'look') return;
        if (type === 'delete') {
            this.dataAggregatorList = this.dataAggregatorList.filter((i, index1) => index1 !== index);
            return;
        }
        this.detailMsg = data;
        this.currentType = type;
        this.currentIndex = index;
        this.aggregatorVisible = true;
    }

    /**
     * 采集器回调事件
     * @param data
     */
    handleAggregatorSubmit(data: any): void {
        if (this.currentType === 'add') {
            this.dataAggregatorList.push(data);
        } else if (this.currentType === 'edit') {
            this.dataAggregatorList.splice(this.currentIndex, 1, data);
        }

        this.detailMsg = {};
        this.currentType = '';
        this.currentIndex = null;
        this.aggregatorVisible = false;

        let fieldList;
        // 获取采集器的字段
        fieldList = this.dataAggregatorList.filter(i => i.processType === 'COMPOSE').map(i => i.logicContext);
        // 获取比较器的字段
        let compare = this.dataComparatorList.map(i => i.checkRuleContext);
        fieldList = [...fieldList, ...compare].join(',');
        this.getfieldTags(fieldList);
    }

    /**
     * 比较器事件
     * @param type 类型 add | look | edit | delete
     * @param data row数据
     * @param index 下标
     */
    handleComparator(type: string, data: any = {}, index: number): void {
        if (this.isLook && type !== 'look') return;
        if (type === 'delete') {
            this.dataComparatorList = this.dataComparatorList.filter((i, index1) => index1 !== index);
            return;
        }
        this.detailMsg = data;
        this.currentType = type;
        this.currentIndex = index;
        this.comparatorVisible = true;
    }

    /**
     * 比较器回调事件
     * @param data
     */
    handleComparatorSubmit(data: any): void {
        if (this.isLook) return;
        if (this.currentType === 'add') {
            this.dataComparatorList.push(data);
        } else if (this.currentType === 'edit') {
            this.dataComparatorList.splice(this.currentIndex, 1, data);
        }

        this.detailMsg = {};
        this.currentType = '';
        this.currentIndex = null;
        this.comparatorVisible = false;

        let fieldList;
        // 获取采集器的字段
        fieldList = this.dataAggregatorList.filter(i => i.processType === 'COMPOSE').map(i => i.logicContext);
        // 获取比较器的字段
        let compare = this.dataComparatorList.map(i => i.checkRuleContext);
        fieldList = [...fieldList, ...compare].join(',');
        this.getfieldTags(fieldList);
    }

    /**
     * 告警器事件
     * @param type 类型 add | look | edit | delete
     * @param data row数据
     * @param index 下标
     */
    handleAlerter(type: string, data: any = {}, index: number): void {
        console.log(data, 'data!!!');

        if (this.isLook && type !== 'look') return;
        if (type === 'delete') {
            this.dataAlerterList = this.dataAlerterList.filter((i, index1) => index1 !== index);
            return;
        }

        this.detailMsg = data;
        this.currentType = type;
        this.currentIndex = index;
        this.alerterVisible = true;
    }

    /**
     * 告警器回调事件
     * @param data
     */
    handleAlerterSubmit(data: any): void {
        if (this.isLook) return;
        if (this.currentType === 'add' || this.currentType === 'auto') {
            this.dataAlerterList.push(data);
        } else if (this.currentType === 'edit') {
            this.dataAlerterList.splice(this.currentIndex, 1, data);
        }

        this.detailMsg = {};
        this.currentType = '';
        this.currentIndex = null;
        this.alerterVisible = false;
    }

    /**
     * 预览
     */
    lookColumns() {
        if (this.submitForm.showJson && this.isJsonString(this.submitForm.showJson)) {
            this.emailTableColumns = this.packageColumns(this.submitForm.showJson);
            this.showJsonBoolean = !this.showJsonBoolean;
            return;
        }
        this.emailTableColumns = [];
    }

    /**
     * 将JSON转换为Columns格式
     */
    packageColumns(json): ColumnVO[] {
        if (json && this.isJsonString(json)) {
            let element = JSON.parse(json);
            const list = [];
            for (let i = 0; i < element.length; i++) {
                const obj = element[i];
                for (const key in obj) {
                    list.push({ field: key, title: obj[key] });
                }
            }
            return list;
        }
        return [];
    }

    cancel() {
        this.$emit('removeTab', this.detail.title);
    }

    submit() {
        if (this.isLook) return;
        if (!this.verify()) return;

        this.submitForm.taskList = this.taskList;
        this.submitForm.dataAggregatorList = this.dataAggregatorList;
        this.submitForm.dataComparatorList = this.dataComparatorList;
        this.submitForm.dataAlerterList = this.dataAlerterList;

        if (this.type === 'add' || this.type === 'copy') {
            API.addMonitorRule(this.submitForm).then((res: any) => {
                this.yh_message_success(this.type === 'add' ? '新增成功!' : '复制成功!');
                this.$emit('removeTab', this.detail.title);
            });
        }
        if (this.type === 'edit') {
            API.editMonitorRule(this.submitForm).then((res: any) => {
                this.yh_message_success('编辑成功!');
                this.$emit('removeTab', this.detail.title);
            });
        }
    }

    verify() {
        if (!this.submitForm.ruleName) {
            this.yh_message_warn('监控规则名称不能为空!');
            return false;
        }
        if (this.taskList.length === 0) {
            this.yh_message_warn('监控频率不能为空!');
            return false;
        }
        if (this.taskList.length > 0) {
            for (let i = 0; i < this.taskList.length; i++) {
                if (!this.taskList[i].expression) {
                    this.yh_message_warn('表达式不能为空!');
                    return false;
                }
            }
        }
        if (this.dataAggregatorList.length === 0) {
            this.yh_message_warn('采集器不能为空!');
            return false;
        }
        if (this.dataComparatorList.length === 0) {
            this.yh_message_warn('比较器不能为空!');
            return false;
        }
        // if (this.dataAlerterList.length === 0) {
        //     this.yh_message_warn('告警器不能为空!');
        //     return false;
        // }
        if (!this.submitForm.showJson) {
            this.yh_message_warn('可视化JSON不能为空!');
            return false;
        }
        return true;
    }

    // 判断是否为json数据
    isJsonString(str: string) {
        try {
            if (typeof JSON.parse(str) == 'object') {
                return true;
            }
        } catch (e) {
            this.yh_message_error('JSON格式有误, 请重新配置JSON!');
        }
        return false;
    }

    changeCron() {}

    /**
     * 表头输入事件 智能提示
     */
    handleInput(val): void {}

    handleTag(str): void {
        str = typeof str === 'string' ? str : JSON.stringify(str);
        // 设置光标起始位置
        let startPos = (document.getElementById('myInput') as any).selectionStart;
        let endPos = (document.getElementById('myInput') as any).selectionEnd;

        this.submitForm.showJson = this.addStrPos(this.submitForm.showJson, startPos, endPos, str);
        // 提前得到更新后的光标位置
        this.$nextTick(() => {
            (document.getElementById('myInput') as any).selectionStart = startPos + str.length;
            (document.getElementById('myInput') as any).selectionEnd = startPos + str.length;
        });
        document.getElementById('myInput').focus();
    }

    addStrPos(str, startind, endind, newstr) {
        return str.slice(0, startind) + newstr + str.slice(endind);
    }

    getfieldTags(str): void {
        this.items = [];
        // var str =
        //     'YH_C_HS_INNER_CODE,HS_VC_INTER_CODE","YH_C_STOCK_TYPE,HS_C_STOCK_TYPE"], (YH_C_HS_INNER_CODE=HS_VC_INTER_CODE) && (YH_C_STOCK_TYPE=HS_C_STOCK_TYPE)';
        var regex = /([a-zA-Z]+_[a-zA-Z]+_[a-zA-Z]+_[a-zA-Z]+)/g; // 下划线命名法的正则表达式
        var match;
        while ((match = regex.exec(str)) !== null) {
            console.log(match[1]); // 输出匹配到的下划线命名法的字段
            this.items.push({ type: '', label: match[1] });
        }
    }
}
</script>
<style lang="scss" scoped>
#monitor-rule-detail {
    // height: 100%;
    padding: 0 5px;
    // overflow: hidden;

    .title-with-box {
        border: 1px solid #dcdfe6;
        border-top: none;

        // /deep/ .el-divider--horizontal {
        //     height: 2px;
        // }

        /deep/ .el-divider__text {
            padding: 0 15px;
            font-weight: 600;
            font-size: 15px;
        }

        /deep/ .el-form-item {
            padding: 0 5px;
            margin-bottom: 10px;
        }

        .frequency-box {
            margin-bottom: 10px;

            /deep/ .el-col-2 {
                text-align: right;
                padding-right: 20px;
                line-height: 28px;

                .el-icon-plus,
                .el-icon-minus {
                    font-size: 17px;
                    font-weight: 600;
                    cursor: pointer;
                }
            }
        }

        .logic-box {
            display: flex;
            padding: 0 10px 10px 10px;

            .flex1 {
                flex: 1;

                /deep/ .el-button {
                    padding: 4px 10px;
                    border-radius: 7px;
                    .el-icon-plus {
                        font-weight: 600;
                    }
                }
            }

            /deep/ .el-card__body {
                padding: 10px;
            }
            p {
                padding-left: 5px;
                margin-bottom: 10px;
            }

            li {
                position: relative;
                border: 1px solid #dcdfe6;
                margin-bottom: -1px;
                border-radius: 4px;
                // height: 30px;
                // line-height: 30px;
                padding: 4px 10px;

                .btn {
                    position: absolute;
                    right: 0;
                    top: 4px;
                }
                .title,
                .link {
                    color: #0000ffd7;
                }

                .link {
                    cursor: pointer;
                    margin-right: 15px;
                }
            }
        }
    }

    .red {
        color: red !important;
    }

    .link {
        color: #0000ffd7;
        cursor: pointer;
        margin-right: 15px;
    }

    .search-bar {
        border: 1px solid #d7d7d7;
        margin: 10px 0;
        padding: 0 5px;
        height: 50px;
        line-height: 50px;
    }
}

.tags {
    margin: 5px;
}

/***  collapse-tags样式 ***/
/deep/ span.el-tag.el-tag--info.el-tag--mini.el-tag--light {
    display: flex;
    align-items: center;
    width: 100%;
    max-width: fit-content;
    padding: 0px 5px 0 0;
    margin: 4px 0px 2px 2px;
    .el-select__tags-text {
        display: inline-block;
        font-size: 12px;
        overflow: hidden;
        text-overflow: ellipsis;
    }
}
/deep/ span.el-tag.el-tag--info.el-tag--mini.el-tag--light:first-of-type {
    width: 63%;
}
/deep/ span.el-tag.el-tag--info.el-tag--mini.el-tag--light:last-of-type {
    width: 100%;
}
/***  collapse-tags样式 ***/
</style>
